package com.yuyu.qingmangmall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuyu.common.exception.NotStockException;
import com.yuyu.common.to.OrderTo;
import com.yuyu.common.utils.PageUtils;
import com.yuyu.common.utils.Query;
import com.yuyu.common.utils.R;
import com.yuyu.common.vo.SocialMemberVo;
import com.yuyu.qingmangmall.order.constant.OrderConstant;
import com.yuyu.qingmangmall.order.dao.OrderDao;
import com.yuyu.qingmangmall.order.entity.OrderEntity;
import com.yuyu.qingmangmall.order.entity.OrderItemEntity;
import com.yuyu.qingmangmall.order.entity.PaymentInfoEntity;
import com.yuyu.qingmangmall.order.enume.OrderStatusEnum;
import com.yuyu.qingmangmall.order.feign.CartFeignService;
import com.yuyu.qingmangmall.order.feign.MemberFeignService;
import com.yuyu.qingmangmall.order.feign.ProductFeignService;
import com.yuyu.qingmangmall.order.feign.WareFeignService;
import com.yuyu.qingmangmall.order.interceptor.OrderWebInterceptor;
import com.yuyu.qingmangmall.order.service.OrderItemService;
import com.yuyu.qingmangmall.order.service.OrderService;
import com.yuyu.qingmangmall.order.service.PaymentInfoService;
import com.yuyu.qingmangmall.order.to.OrderCreateTo;
import com.yuyu.qingmangmall.order.vo.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> threadLocal = new ThreadLocal<>();

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    PaymentInfoService paymentInfoService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo orderConfirm() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        SocialMemberVo memberVo = OrderWebInterceptor.threadLocal.get();

        System.out.println("主线程Id: "+Thread.currentThread().getId());

        // 老请求的数据
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 异步编排
        CompletableFuture<Void> memberAddressFuture = CompletableFuture.runAsync(() -> {
            System.out.println("Address线程Id: "+Thread.currentThread().getId());
            // 将主线程老请求的数据放入新线程
            RequestContextHolder.setRequestAttributes(requestAttributes);
            // 1. 远程查询所有的收货地址列表
            List<MemberAddressVo> memberReceiveAddress = memberFeignService.getMemberReceiveAddress(memberVo.getId());

            confirmVo.setAddressVos(memberReceiveAddress);
            // 3. 查询用户积分
            confirmVo.setIntegration(memberVo.getIntegration());

        }, executor);

        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            System.out.println("cart线程Id: "+Thread.currentThread().getId());
            // 将主线程老请求的数据放入新线程
            RequestContextHolder.setRequestAttributes(requestAttributes);

            // 2. 远程查询购物车所有选中的购物项
//        productFeignServer.getNewPrices()
            List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();

            confirmVo.setItemVos(currentUserCartItems);
            // feign在远程调用之前要构造请求，调用很多拦截器
            // RequestInterceptor interceptor ：requestInterceptors
        }, executor).thenRunAsync(()->{
            List<OrderItemVo> itemVos = confirmVo.getItemVos();
            List<Long> skuIds = itemVos.stream().map(OrderItemVo::getSkuId).collect(Collectors.toList());
            R r = wareFeignService.getSkusHasStock(skuIds);
            List<SkuHasStockVo> data = r.getData(new TypeReference<List<SkuHasStockVo>>() {
            });
            Map<Long, Boolean> hasStockMap = data.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
            confirmVo.setHasStockMap(hasStockMap);
        },executor);

        // 4. 其他数据自动计算

        // TODO 5. 防重令牌
        String replace = UUID.randomUUID().toString().replace("-", "");
        confirmVo.setOrderToken(replace);
        // 将令牌放入redis中
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberVo.getId(),replace,30, TimeUnit.MINUTES);

        CompletableFuture.allOf(memberAddressFuture,cartFuture).get();

        return confirmVo;
    }

    /**
     *
     * @param vo
     * @return
     * @Transactional: 在分布式系统中，只能控制自己的回滚，控制不了其他服务回滚
     *  分布式事务：最大原因。网络问题+分布式机器。
     */
//    @GlobalTransactional  不适合大并发的订单服务
    @Transactional //
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        threadLocal.set(vo);
        // 下单成功来支付选择页
        // 下单失败回到订单确认页重新确认订单的信息
        SocialMemberVo memberVo = OrderWebInterceptor.threadLocal.get();

        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        // 1. 验证令牌【令牌的对比和删除必须保证原子性】
        // 0令牌失败 - 1令牌成功
        String orderToken = vo.getOrderToken();
        //              if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        // 原子验证令牌和删除令牌
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberVo.getId()), orderToken);
        if (result==0L){
            // 令牌验证失败
            responseVo.setCode(1); // 令牌验证失败
            return responseVo;
        }else {
            // 验证成功
            // 下单，去创建订单，验令牌，验价格，锁库存。。。
            // 1. 创建订单订单项等信息
            OrderCreateTo order = createOrder();
            // 2. 验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue())<0.01){
                // 验价成功
                // ...
                // 3.保存订单
                saveOrder(order);
                // 4.库存锁定。只要有异常回滚订单数据
                WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
                wareSkuLockVo.setOrderSn(order.getOrder().getOrderSn());

                List<OrderItemVo> orderItemVos = order.getOrderItems().stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setTitle(item.getSkuName());
                    orderItemVo.setCount(item.getSkuQuantity());
                    return orderItemVo;
                }).collect(Collectors.toList());

                wareSkuLockVo.setLocks(orderItemVos);
                // TODO 4.远程锁库存
                // 库存成功了，但是网络原因超时了，订单回滚，库存不滚
                R r = wareFeignService.orderLockStock(wareSkuLockVo);
                if (r!=null && r.getCode()==0) {
                    // 锁定成功
                    responseVo.setCode(0);
                    responseVo.setOrder(order.getOrder());

                    // TODO 5.远程扣减积分，出现异常
//                    int i = 10/0; // 订单回滚，库存不滚
                    // TODO 订单创建完成发送消息给MQ
                    rabbitTemplate.convertAndSend("order-event-exchange",
                            "order.create.order",order.getOrder());
                    return responseVo;
                } else {
                    // 锁定失败
                    responseVo.setCode(3);
                    Object msg = r.get("msg");
                    throw new NotStockException(2L);
//                    return responseVo;
                }

                // 订单号，所有订单项（skuId，skuName，num）
            } else {
                responseVo.setCode(2); // 验价失败
                return responseVo;
            }

        }


//        String orderToken = vo.getOrderToken();
        // 需要保证原子操作
//        String redisToken = redisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberVo.getId());
//        if (orderToken!=null && orderToken.equals(redisToken)){
//            // 验证通过
//            redisTemplate.delete(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberVo.getId());
//        }else{
//        // 不通过
//        }
    }

    @Override
    public OrderEntity getByOrderSn(String orderSn) {
        OrderEntity orderEntity = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return orderEntity;
    }

    /**
     * 关闭订单（修改订单状态）
     * @param orderEntity
     */
    @Override
    public void closeOrder(OrderEntity orderEntity) {
        // 查询当前订单的最新状态
        if (orderEntity.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())){
            OrderEntity update = new OrderEntity();
            update.setId(orderEntity.getId());
            // 关单
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity,orderTo);
            // 给MQ发送消息
            try {
                // TODO 保证消息一定会发送出去，每一个消息都可以做好日志记录（给数据库保存每一个消息的详细信息）
                // TODO 定期扫描数据库将失败的消息再发送一遍；
                rabbitTemplate.convertAndSend("order-event-exchange",
                        "order.release.order",orderTo);
            }catch (Exception e){
                // TODO 将没法发送成功的消息进行重试发送。
//                where
            }

        }

    }

    /**
     * 拿到订单的付款相关信息
     * @param orderSn
     * @return
     */
    @Override
    public PayVo getOrderPay(String orderSn) {
        OrderEntity orderEntity = this.getByOrderSn(orderSn);
        PayVo payVo = new PayVo();
        /*
            private String out_trade_no; // 商户订单号 必填
            private String subject; // 订单名称 必填
            private String total_amount;  // 付款金额 必填
            private String body; // 商品描述 可空
         */
        payVo.setOut_trade_no(orderSn);

        BigDecimal totalAmount = orderEntity.getTotalAmount();
        BigDecimal bigDecimal = totalAmount.setScale(2, BigDecimal.ROUND_UP); // 进一
        payVo.setTotal_amount(bigDecimal.toString());


        List<OrderItemEntity> orderItems = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity orderItemEntity = orderItems.get(0);
        payVo.setSubject(orderItemEntity.getSkuName());
        payVo.setBody(orderItemEntity.getSkuAttrsVals());
        return payVo;
    }

    /**
     * 分页查询当前登录用户的所有订单信息
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        SocialMemberVo memberVo = OrderWebInterceptor.threadLocal.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id",memberVo.getId()).orderByDesc("id")
        );

        List<OrderEntity> orderEntityList = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> order_sn = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(order_sn);
            return order;
        }).collect(Collectors.toList());
        
        page.setRecords(orderEntityList);
        return new PageUtils(page);

    }

    /**
     * 处理支付宝的支付结果
     * @param asyncVo
     * @return
     */
    @Override
    public String handlePayResult(PayAsyncVo asyncVo) {

        //保存交易流水信息
        PaymentInfoEntity paymentInfo = new PaymentInfoEntity();
        paymentInfo.setOrderSn(asyncVo.getOut_trade_no());
        paymentInfo.setAlipayTradeNo(asyncVo.getTrade_no());
        paymentInfo.setTotalAmount(new BigDecimal(asyncVo.getBuyer_pay_amount()));
        paymentInfo.setSubject(asyncVo.getBody());
        paymentInfo.setPaymentStatus(asyncVo.getTrade_status());
        paymentInfo.setCreateTime(new Date());
        paymentInfo.setCallbackTime(asyncVo.getNotify_time());

        paymentInfoService.save(paymentInfo);

        String tradeStatus = asyncVo.getTrade_status(); // 支付宝提交的订单状态
        // 修改订单状态信息
        if (tradeStatus.equals("TRADE_SUCCESS") || tradeStatus.equals("TRADE_FINISHED")){
            // 支付成功状态
            String outTradeNo = asyncVo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(outTradeNo,OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }

    /**
     * 保存订单
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);

        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);

    }


    private OrderCreateTo createOrder(){
        OrderCreateTo createTo = new OrderCreateTo();
        // 1.生成订单号
        String orderSn = IdWorker.getTimeId();
        OrderEntity orderEntity = buildOrder(orderSn);
        createTo.setOrder(orderEntity);

        // 2. 创建所有订单项
        List<OrderItemVo> orderItemVos = cartFeignService.getCurrentUserCartItems();
        List<OrderItemEntity> orderEntities = null;
        if (orderItemVos!=null && orderItemVos.size()>0){
            orderEntities = buildOrderItems(orderSn,orderItemVos);
            createTo.setOrderItems(orderEntities);
        }

        //3. 计算价格相关
        if (orderEntities!=null && orderEntities.size()>0){
            computePrice(orderEntity,orderEntities);
        }

        return createTo;
    }

    /**
     * 计算价格的方法
     * @param orderEntity
     * @param orderItemEntities
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {

        //总价
        BigDecimal total = new BigDecimal("0.0");
        //优惠价
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal intergration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");

        //积分、成长值
        Integer integrationTotal = 0;
        Integer growthTotal = 0;

        //订单总额，叠加每一个订单项的总额信息
        for (OrderItemEntity orderItem : orderItemEntities) {
            //优惠价格信息
            coupon = coupon.add(orderItem.getCouponAmount());
            promotion = promotion.add(orderItem.getPromotionAmount());
            intergration = intergration.add(orderItem.getIntegrationAmount());

            //总价
            total = total.add(orderItem.getRealAmount());

            //积分信息和成长值信息
            integrationTotal += orderItem.getGiftIntegration();
            growthTotal += orderItem.getGiftGrowth();

        }
        //1、订单价格相关的
        orderEntity.setTotalAmount(total);
        //设置应付总额(总额+运费)
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setCouponAmount(coupon);
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(intergration);

        //设置积分成长值信息
        orderEntity.setIntegration(integrationTotal);
        orderEntity.setGrowth(growthTotal);

        //设置删除状态(0-未删除，1-已删除)
        orderEntity.setDeleteStatus(0);

    }

    private List<OrderItemEntity> buildOrderItems(String orderSn,List<OrderItemVo> orderItemVos) {
        List<OrderItemEntity> orderEntityList = orderItemVos.stream().map(orderItemVo -> {
            OrderItemEntity orderItemEntity = buildOrderItem(orderItemVo);
            orderItemEntity.setOrderSn(orderSn);
            return orderItemEntity;
        }).collect(Collectors.toList());

        return orderEntityList;
    }

    /**
     * 创建单个订单项
     * @param orderItemVo
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo orderItemVo) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        // 1.设置Sku
        orderItemEntity.setSkuId(orderItemVo.getSkuId());
        orderItemEntity.setSkuName(orderItemVo.getTitle()); // 标题
        String skuAttrValues = StringUtils.collectionToDelimitedString(orderItemVo.getSkuAttr(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttrValues);
        orderItemEntity.setSkuPic(orderItemVo.getImage());
        orderItemEntity.setSkuPrice(orderItemVo.getPrice());
        orderItemEntity.setSkuQuantity(orderItemVo.getCount());

        // 2.远程调用商品服务设置spu
        R r = productFeignService.getSpuBySkuId(orderItemVo.getSkuId());
        if (r!=null && r.getCode()==0){
            SpuInfoVo spuInfoVo = r.getData(new TypeReference<SpuInfoVo>() {
            });
            orderItemEntity.setSpuId(spuInfoVo.getId());
            orderItemEntity.setSpuName(spuInfoVo.getSpuName());
            orderItemEntity.setCategoryId(spuInfoVo.getCatalogId());
        }

        // 3. 商品的优惠信息[不做]

        // 4.积分信息
        //  orderItemEntity.setGiftGrowth(orderItemVo.getPrice().intValue());
        //  orderItemEntity.setGiftIntegration(orderItemVo.getPrice().intValue());
        orderItemEntity.setGiftGrowth(orderItemVo.getPrice().multiply(new BigDecimal(orderItemVo.getCount())).intValue());
        orderItemEntity.setGiftIntegration(orderItemVo.getPrice().multiply(new BigDecimal(orderItemVo.getCount())).intValue());


        //5、订单项的价格信息
        orderItemEntity.setPromotionAmount(BigDecimal.ZERO);
        orderItemEntity.setCouponAmount(BigDecimal.ZERO);
        orderItemEntity.setIntegrationAmount(BigDecimal.ZERO);

        //当前订单项的实际金额.总额 - 各种优惠价格
        //原来的价格
        BigDecimal origin = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        //原价减去优惠价得到最终的价格
        BigDecimal subtract = origin.subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(subtract);

        return orderItemEntity;
    }

    private OrderEntity buildOrder(String orderSn) {
        // 2.创建订单
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        // 3.获取收获地址信息
        OrderSubmitVo submitVo = threadLocal.get();
        R fare = wareFeignService.getFare(submitVo.getAddrId());
        if (fare!=null && fare.getCode()==0){
            FareVo fareData = fare.getData(new TypeReference<FareVo>() {
            });
            MemberAddressVo addressVo = fareData.getAddressVo();
            // 设置运费信息
            orderEntity.setFreightAmount(fareData.getFare());
            orderEntity.setMemberId(addressVo.getMemberId());
            // 设置收货人信息
            orderEntity.setReceiverName(addressVo.getName()); // 收货人姓名
            orderEntity.setReceiverCity(addressVo.getCity()); // 城市
            orderEntity.setReceiverPhone(addressVo.getPhone()); // 电话
            orderEntity.setReceiverPostCode(addressVo.getPostCode()); // 邮政编码
            orderEntity.setReceiverProvince(addressVo.getProvince()); // 省份/直辖市
            orderEntity.setReceiverRegion(addressVo.getRegion()); // 区
            orderEntity.setReceiverDetailAddress(addressVo.getDetailAddress()); // 详细地址(街道)
        }
        //设置订单相关的状态信息
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(15);
        orderEntity.setConfirmStatus(0);


        return orderEntity;
    }
}